package com.wsoft.dc.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsoft.constant.redis.RedisKeyConstant;
import com.wsoft.core.service.RedisService;
import com.wsoft.dc.entity.DcBusinessReadEntity;
import com.wsoft.dc.enums.ReadTypeEnum;
import com.wsoft.dc.mapper.DcBusinessReadMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author z001
 * @Date 2024/10/23 09:08
 */
@Service
public class DcBusinessReadManager extends ServiceImpl<DcBusinessReadMapper, DcBusinessReadEntity> {

    @Resource
    private RedisService redisService;

    /**
     * 判断是否已读
     * @param configId
     * @param key
     * @param memberId
     * @return
     */
    public DcBusinessReadEntity getReadInfo(Long configId,String key,Long memberId){
        QueryWrapper<DcBusinessReadEntity> query = new QueryWrapper<>();
        query.lambda().eq(DcBusinessReadEntity::getConfigId,configId)
                .eq(DcBusinessReadEntity::getMemberId,memberId)
                .eq(DcBusinessReadEntity::getKey,key);
        return getOne(query);
    }

    /**
     * 根据用户获取已读
     * @param memberId
     * @param configId
     * @return
     */
    public Set<String> getMemberRead(Long memberId,Long configId){
        Set<Object> set = redisService.sMembers(RedisKeyConstant.Config.MEMBER_READ + memberId + StrUtil.COLON + configId);
        if(CollUtil.isNotEmpty(set)){
            return set.stream().map(String::valueOf).collect(Collectors.toSet());
        }

        QueryWrapper<DcBusinessReadEntity> query = new QueryWrapper<>();
        query.lambda().eq(DcBusinessReadEntity::getMemberId,memberId)
                .eq(DcBusinessReadEntity::getReadFlag, ReadTypeEnum.READ.getType())
                .eq(DcBusinessReadEntity::getConfigId,configId);
        List<DcBusinessReadEntity> list = list(query);
        if(CollUtil.isEmpty(list)){
            return new HashSet<>();
        }
        Set<String> collect = list.stream().map(DcBusinessReadEntity::getKey).collect(Collectors.toSet());
        for (String item : collect) {
            redisService.sAdd(RedisKeyConstant.Config.MEMBER_READ + memberId + StrUtil.COLON + configId,item);
        }
        return collect;
    }

    /**
     * 移除未读记录
     * @param memberId
     * @return
     */
    public boolean removeUnRead(Long memberId){
        QueryWrapper<DcBusinessReadEntity> query = new QueryWrapper<>();
        query.lambda().eq(DcBusinessReadEntity::getMemberId,memberId)
                .eq(DcBusinessReadEntity::getReadFlag, ReadTypeEnum.UNREAD.getType());
       return remove(query);
    }
}
